package com.fmsh.nfcsensor.activity;


import android.app.Dialog;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fmsh.base.adapter.BaseRecyclerAdapter;
import com.fmsh.base.handler.BaseHandler;
import com.fmsh.base.handler.UIHandlerCallback;
import com.fmsh.base.ui.BaseNFCActivity;
import com.fmsh.base.ui.NFCReaderCallback;
import com.fmsh.base.utils.HintDialog;
import com.fmsh.base.utils.LogUtil;
import com.fmsh.base.utils.UIUtils;
import com.fmsh.nfcsensor.R;
import com.fmsh.nfcsensor.adapter.SensorAdapter;
import com.fmsh.nfcsensor.bean.IncomeBean;
import com.fmsh.nfcsensor.bean.SensorBean;
import com.fmsh.nfcsensor.tools.MyThread;
import com.fmsh.nfcsensor.tools.chart.FullScreenDialog;
import com.fmsh.nfcsensor.tools.chart.LineChartManager;
import com.fmsh.nfcsensor.tools.chart.LineChartManagerUtils;
import com.fmsh.nfcsensor.utils.Constants;
import com.github.mikephil.charting.charts.LineChart;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.ArrayList;

import butterknife.BindView;


public class MainActivity extends BaseNFCActivity implements UIHandlerCallback {


    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    private QMUITipDialog mQmuiTipDialog;
    private SensorAdapter mSensorAdapter;
    private ArrayList<SensorBean> mList;
    private LineChartManagerUtils chartManager;
    private LineChart mLine_chart;
    private QMUITopBarLayout mDialogTopbar;
    private Dialog mDialog;
    private LineChartManager mLineChartManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        String version = "1.0.0";
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();


        }
        //
        setTitle(UIUtils.getString(this, R.string.app_name) + version);

        mQmuiTipDialog = HintDialog.loadingDialog(MainActivity.this, UIUtils.getString(mContext, R.string.loading));
    }

    @Override
    protected void initData() {


        recycler.setLayoutManager(new LinearLayoutManager(mContext));

        mSensorAdapter = new SensorAdapter(mContext);
        recycler.setAdapter(mSensorAdapter);
        mSensorAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {


            @Override
            public void itemClickListener(int position) {
                //                Bundle bundle = new Bundle();
                //                bundle.putParcelable(Constants.KEY_HANDLE_SEND_MSG, mList.get(position));
                //                bundle.putParcelableArrayList(Constants.KEY_HANDLE_SEND_MSG+1,mList);
                //                startActivity(bundle, ChartActivity.class);
                View inflate = LayoutInflater.from(mContext).inflate(R.layout.activity_chart, null);
                LinearLayout ll_hint = inflate.findViewById(R.id.ll_hint);
                LinearLayout ll_switch = inflate.findViewById(R.id.ll_switch);
                mLine_chart = inflate.findViewById(R.id.line_chart);
                mDialogTopbar = inflate.findViewById(R.id.topbar);
                Spinner spinner = inflate.findViewById(R.id.spinner);
                ll_hint.setVisibility(View.GONE);
//                ll_switch.setVisibility(View.VISIBLE);
//                mLine_chart.setVisibility(View.VISIBLE);
                String[] mSensorArray = new String[mList.size()];

                for (int i = 0; i < mList.size(); i++) {
                    String type = UIUtils.getString(mContext, mList.get(i).getTypeId());
                    mSensorArray[i] = type + "传感器";
//                    if (type.equals(UIUtils.getString(mContext, mList.get(position).getTypeId()))) {
//                        currentSelect = i;
//                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, mSensorArray);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);
                spinner.setSelection(position);
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        SensorBean sensorBean = mList.get(position);
                        switchChart(sensorBean);

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
//                switchChart(mList.get(position));
                mDialog = new FullScreenDialog(mContext,
                        android.R.style.Theme_DeviceDefault_Light_NoActionBar, inflate);
                mDialog.setCancelable(true);
                mDialog.show();
                mDialogTopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();
                    }
                });

            }
        });


    }

    private int currentSelectType;
    private void switchChart(SensorBean sensorBean){
        currentSelectType = sensorBean.getType();
        switch (sensorBean.getType()) {
            case Constants.T_VALUE:
                initTemperatureChart(sensorBean);
                break;
            case Constants.H_VALUE:
                initHumidityChart(sensorBean);
                break;
            case Constants.P_VALUE:
                initPressureChart(sensorBean);
                break;
            case Constants.B_VALUE:
                initBrightnessChart(sensorBean);
                break;
            case Constants.NOX_VALUE:
                initGasNOXChart(sensorBean);
                break;
            case Constants.VOC_VALUE:
                initGasVOCChart(sensorBean);
                break;
            case Constants.CO2_VALUE:
                initGasCO2Chart(sensorBean);
                break;
        }
    }

    public void initTemperatureChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.temperature_chart));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 5), (float) (sensorBean.getValue() - 5), 5);
        mLineChartManager.showLineChart(mTList, UIUtils.getString(mContext, R.string.temperature_chart) + "/" + sensorBean.getUnity());
    }

    public void initHumidityChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.humidity_chart));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 5), (float) (sensorBean.getValue() - 5), 5);
        mLineChartManager.showLineChart(mHList,UIUtils.getString(mContext, R.string.humidity_chart) + "/" + sensorBean.getUnity());

    }

    public void initPressureChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.pressure_chart));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 200), (float) (sensorBean.getValue() - 200), 5);
        mLineChartManager.showLineChart(mPList,UIUtils.getString(mContext, R.string.pressure_chart) + "/" + sensorBean.getUnity(),true);

    }

    public void initBrightnessChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.brightness_chart));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 500), (float) (sensorBean.getValue() - 500), 5);
        mLineChartManager.showLineChart(mBList,UIUtils.getString(mContext, R.string.brightness_chart) + "/" + sensorBean.getUnity());

    }
    public void initGasNOXChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.gas_chart_nox));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 5), (float) (sensorBean.getValue() - 5), 5);
        mLineChartManager.showLineChart(mNOXList,UIUtils.getString(mContext, R.string.gas_chart_nox) + "/" + sensorBean.getUnity(),true);

    }
    public void initGasVOCChart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.gas_chart_voc));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 200), (float) (sensorBean.getValue() - 200), 5);
        mLineChartManager.showLineChart(mVOCList,UIUtils.getString(mContext, R.string.gas_chart_voc) + "/" + sensorBean.getUnity(),true);

    }

    public void initGasCO2Chart(SensorBean sensorBean) {
        mDialogTopbar.setTitle(UIUtils.getString(mContext, R.string.gas_chart_CO2));
        mLineChartManager = new LineChartManager(mLine_chart);
        mLineChartManager.setYAxisData((float) (sensorBean.getValue() + 3000), (float) (sensorBean.getValue() - 200), 5);
        mLineChartManager.showLineChart(mCO2List,UIUtils.getString(mContext, R.string.gas_chart_CO2) + "/" + sensorBean.getUnity(),true);

    }

    @Override
    protected void onResume() {
        super.onResume();

        setNfcReaderCallback(new NFCReaderCallback() {
            @Override
            public void onTagDiscovered(Tag tag) {
                send();
            }
        });
    }

    private void send() {
        mQmuiTipDialog.show();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.KEY_NFC_TAG, mTag);
        bundle.putInt(Constants.KEY_NFCA_OPERATION_TYPE, 0);
        Message message = new Message();
        message.what = 0;
        message.setData(bundle);
        MyThread.getInstance().getRunHandler().sendMessage(message);
        BaseHandler.getInstance().setUIHandlerCallback(this);

    }
    private ArrayList<IncomeBean> mTList = new ArrayList<>();
    private ArrayList<IncomeBean> mHList = new ArrayList<>();
    private ArrayList<IncomeBean> mBList = new ArrayList<>();
    private ArrayList<IncomeBean> mPList = new ArrayList<>();
    private ArrayList<IncomeBean> mNOXList = new ArrayList<>();
    private ArrayList<IncomeBean> mVOCList = new ArrayList<>();
    private ArrayList<IncomeBean> mCO2List = new ArrayList<>();
    private int mLinCount = 6;
    private void addSensorData(ArrayList<SensorBean> list) {
        for (int i = 0; i < list.size(); i++) {
            SensorBean sensorBean = list.get(i);
            switch (sensorBean.getType()) {
                case Constants.T_VALUE:
                    if (mTList.size()>=mLinCount){
                        mTList.remove(0);
                    }
                    //mTList.add(Float.parseFloat(String.format("%.2f",sensorBean.getValue())));
                    mTList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    LogUtil.d("addSensorData",mTList.size());
                    if(mLineChartManager != null && currentSelectType == Constants.T_VALUE){
                        mLineChartManager.showLineChart(mTList, UIUtils.getString(mContext, R.string.temperature_chart) + "/" + sensorBean.getUnity());
                    }
                    break;
                case Constants.B_VALUE:
                    if (mBList.size()>=mLinCount){
                        mBList.remove(0);
                    }
                    mBList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.B_VALUE){
                        mLineChartManager.showLineChart(mBList, UIUtils.getString(mContext, R.string.brightness_chart) + "/" + sensorBean.getUnity());
                    }
                    break;
                case Constants.H_VALUE:
                    if (mHList.size()>=mLinCount){
                        mHList.remove(0);
                    }
                    mHList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.H_VALUE){
                        mLineChartManager.showLineChart(mHList, UIUtils.getString(mContext, R.string.humidity_chart) + "/" + sensorBean.getUnity());
                    }
                    break;
                case Constants.P_VALUE:
                    if (mPList.size()>=mLinCount){
                        mPList.remove(0);
                    }
                    mPList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.P_VALUE){
                        mLineChartManager.showLineChart(mPList, UIUtils.getString(mContext, R.string.pressure_chart) + "/" + sensorBean.getUnity(),true);
                    }
                    break;
                case Constants.NOX_VALUE:
                    if (mNOXList.size()>=mLinCount){
                        mNOXList.remove(0);
                    }
                    mNOXList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.NOX_VALUE){
                        mLineChartManager.showLineChart(mNOXList, UIUtils.getString(mContext, R.string.gas_chart_nox) + "/" + sensorBean.getUnity(),true);
                    }
                    break;
                case Constants.VOC_VALUE:
                    if (mVOCList.size()>=mLinCount){
                        mVOCList.remove(0);
                    }
                    mVOCList.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.VOC_VALUE){
                        mLineChartManager.showLineChart(mVOCList, UIUtils.getString(mContext, R.string.gas_chart_voc) + "/" + sensorBean.getUnity(),true);
                    }
                    break;
                case Constants.CO2_VALUE:
                    if (mCO2List.size()>=mLinCount){
                        mCO2List.remove(0);
                    }
                    mCO2List.add(new IncomeBean(sensorBean.getTime(),sensorBean.getValue()));
                    if(mLineChartManager != null && currentSelectType == Constants.CO2_VALUE){
                        mLineChartManager.showLineChart(mCO2List, UIUtils.getString(mContext, R.string.gas_chart_CO2) + "/" + sensorBean.getUnity(),true);
                    }
                    break;
            }
        }
    }

    @Override
    public void callback(int what, Bundle bundle) {
        LogUtil.d(TAG);
        mQmuiTipDialog.dismiss();
        switch (what) {
            case Constants.SUCCESS_RESULT:
                if (bundle != null) {
                    mList = bundle.getParcelableArrayList(Constants.KEY_HANDLE_SEND_MSG);
                    LogUtil.d(mList.size());
                    llHint.setVisibility(View.GONE);
                    recycler.setVisibility(View.VISIBLE);
                    mSensorAdapter.setList(mList);
                    addSensorData(mList);
                }
                break;
            case Constants.NFC_UNKNOWN_ERROR:
                if (mSensorAdapter.mList.isEmpty()) {
                    HintDialog.faileDialog(mContext, UIUtils.getString(mContext, R.string.nfc_communication_failure));
                }
                break;
            case Constants.NFC_NO_TYPE_NFCA:
                HintDialog.faileDialog(mContext, UIUtils.getString(mContext, R.string.nfc_card_type_error));
                break;
            case Constants.NFC_AUTH_FAILED:
                HintDialog.faileDialog(mContext, UIUtils.getString(mContext, R.string.nfc_card_auth_failed));
                break;
            case Constants.NFC_NO_SENSOR:
                HintDialog.faileDialog(mContext, UIUtils.getString(mContext, R.string.nfc_no_sensor));

                break;
            case 10:

                break;

        }

    }

}